<?php

/**
 * @author 
 * @copyright 2008
 */
$err = new ErrorWizard;
$table_video_catalog = PFX."video_catalog";
$table_video_tree = PFX."video_tree";
$table_video_videos = PFX."video_videos";
$table_video_images = PFX."video_images";
$table_category = PFX."category";
/** per_page */
$per_page = 5;if(isset($_REQUEST['per_page']) and intval($_REQUEST['per_page']) > 0){$per_page = intval($_REQUEST['per_page']);}
/** from */
$from = 0;if(isset($_REQUEST['from']) and intval($_REQUEST['from']) > 0){$from = intval($_REQUEST['from']);}
/** lim_from */
$lim_from = $from*$per_page;
$item_id = 0;
$cat_id = 0;
$mod_path = $this->fetchPath($this->path);
if(!empty($mod_path))
{
	if(isset($mod_path[0]))
	{
		$is_item = preg_match("/^(\d+)$/",strval($mod_path[0]),$mod_parse['item']);
		$is_cat = preg_match("/^cat_(\d+)$/",strval($mod_path[0]),$mod_parse['cat']);
		if($is_item > 0 and intval($mod_parse['item'][1]) > 0){$item_id = intval($mod_parse['item'][1]);}
		elseif($is_cat > 0 and intval($mod_parse['cat'][1]) > 0){$cat_id = intval($mod_parse['cat'][1]);}
	}
}
/** do */
$do = '';if(isset($_REQUEST['do']) and !empty($_REQUEST['do'])){$do = strval($_REQUEST['do']);}
/** START 	//TODO: Add/Edit/Delete Item
 */
//TODO: Item->Add
/** START 	Add Item */
if($do == 'add')
{
	$item = $_POST['item'];
	unset($_POST['item']);
	$error = false;
	$error_text = array();
	/** START 	проверка */
	if(empty($item['title'])){$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_NO_TITLE','add_item','video'));}
	if(empty($item['alias'])){$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_NO_ALIAS','add_item','video'));}
	elseif($db->fetch_one("SELECT * FROM $table_video_catalog WHERE alias = '".strval($item['alias'])."'") != false)
	{$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_DUPLICATED_ALIAS','add_item','video'));}
	/** END 	проверка */
	if($error)
	{
		$_SESSION['message'] = '<p class="error">'.implode('</p><p class="error">',$error_text).'</p>';
		$smarty->assign("item",$item);
	}
	else
	{
		$insert_item_data = array(
			'title' 		=> strval($item['title']),
			'short_title' 	=> strval($item['short_title']),
			'alias' 		=> strval($item['alias']),
			'content' 		=> strval($item['content']),
			'status' 		=> intval($item['status']),
			'time' 			=> time()
		);
		$inserting_item = $db->insert($table_video_catalog,$insert_item_data);
		$item_id = $db->last_id();
		if(!$inserting_item)
		{$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage($err->getError('ERROR_SQL_INSERT','add_item','video')).'</p>';}
		else
		{
			if(isset($_FILES))
			{
				//print_var($_FILES);
				$upload_errors = false;
				$images = array();
				$videos = array();
				if(isset($_FILES['item']['name']['images']))
				{
					foreach($_FILES['item']['name']['images'] as $n => $name)
					{
						$images[] = array(
							'name' => $name['file'],
							'tmp_name' => $_FILES['item']['tmp_name']['images'][$n]['file'],
							'error' => $_FILES['item']['error']['images'][$n]['file'],
							'type' => $_FILES['item']['type']['images'][$n]['file'],
							'size' => $_FILES['item']['size']['images'][$n]['file']
						);
					}
				}
				if(isset($_FILES['item']['name']['videos']))
				{
					foreach($_FILES['item']['name']['videos'] as $n => $name)
					{
						$videos[] = array(
							'name' => $name['file'],
							'tmp_name' => $_FILES['item']['tmp_name']['videos'][$n]['file'],
							'error' => $_FILES['item']['error']['videos'][$n]['file'],
							'type' => $_FILES['item']['type']['videos'][$n]['file'],
							'size' => $_FILES['item']['size']['videos'][$n]['file']
						);
					}
				}
				if(!empty($images))
				{
					foreach($images as $key=>$file)
					{
						if($file['file'] != '')
						{
							$insert_image = array(
								'pid' => $item_id,
								'title' => strval($item['images'][$key]['title']),
								'main' => (intval($item['images'][$key]['main']) == 1 ? '1' : '0'),
								'status' => intval($item['images'][$key]['status']),
								'time' => time()
							);
							$db->insert($table_video_images,$insert_image);
							$name = $db->last_id();$dir = '/video/images/';$sizes = array(600,300,100);
							$upload_image = upload_image($file,$name,$dir,$sizes);
							if(!$upload_image)
							{
								$upload_errors = true;
								$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage("добавление фотографии $key провалилось из-за ошибки при вставке в БД! Переданный запрос ".$insert_image,__FILE__,__LINE__).'</p>';
								$db->query("DELETE FROM $table_video_images WHERE id = '".intval($db->last_id())."'");
								break;
							}
						}
					}
				}
				if(!empty($videos))
				{
					foreach($videos as $key=>$file)
					{
						if($file['file'] != '')
						{
							$name = $key;$dir = '/video/videos/';$sizes = array(600,300,100);
							$upload_image = upload_video_ajax($file,$name,$dir,$sizes);
							if(!$upload_image){$upload_errors = true;$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage($err->getError('ERROR_SQL_INSERT','add_item','video')).'</p>';break;}
						}
					}
				}
				if($upload_errors){/*header('location: /admin/video/');die();*/}
				
			}
			$_SESSION['message'] = '<p class="success">'.$err->constructErrorMessage($err->getError('NO_ERROR','add_item','video')).'</p>';
			//header('location: /admin/video/');die();
		}
	}
}
/** END 	Add Item */
//TODO: Item->Edit
/** START 	Edit Item */
elseif($do == 'edit')
{
	$item = $_POST['item'];
	unset($_POST['item']);
	$error = false;
	$error_text = array();
	/** START 	проверка */
	//$is_duplicated_alias = $db->fetch_one("SELECT * FROM $table_video_catalog WHERE alias = '".strval($item['alias'])."'");
	if(empty($item['title'])){$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_NO_TITLE','edit_item','video'));}
	if(empty($item['alias'])){$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_NO_ALIAS','edit_item','video'));}
	/*
	elseif($is_duplicated_alias != false)
	{$error = true;$error_text[] = $err->constructErrorMessage($err->getError('ERROR_DUPLICATED_ALIAS','edit_item','video'));}
	*/
	/** END 	проверка */
	if($error)
	{
		$_SESSION['message'] = '<p class="error">'.implode('</p><p class="error">',$error_text).'</p>';
		$smarty->assign("item",$item);
	}
	else
	{
		$item_id = intval($item['id']);
		$item_clause = "WHERE id = '$item_id'";
		$update_item_data = array(
			'title' 		=> strval($item['title']),
			'short_title' 	=> strval($item['short_title']),
			'alias' 		=> strval($item['alias']),
			'content' 		=> strval($item['content']),
			'status' 		=> intval($item['status'])
		);
		$updating_item = $db->update($table_video_catalog,$update_item_data,$item_clause);
		if($updating_item)
		{
			if(isset($item['images']))
			{
				foreach($item['images'] as $i=>$image_data)
				{
					if(isset($image_data['id']) and intval($image_data['id']) > 0)
					{
						$update_image = array();
						$update_image = array(
							'pid' => $item_id,
							'title' => strval($image_data['title']),
							'main' => (intval($image_data['main']) == 1 ? '1' : '0'),
							'status' => intval($image_data['status']),
							'time' => time()
						);
						$update_img_sql_where = '';
						$update_img_sql_where = "WHERE id = '".intval($image_data['id'])."'";
						$res = bool;
						$res = $db->update($table_video_images,$update_image,$update_img_sql_where);
						if(!$res)
						{
							$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage("изменение данных фотографии $i провалилось из-за ошибки при UPDATE в БД!",__FILE__,__LINE__).'</p>';
							$error = true;
							break;
						}
					}
					else
					{
						$insert_image = array();
						$insert_image = array(
							'pid' => $item_id,
							'title' => strval($image_data['title']),
							'main' => (intval($image_data['main']) == 1 ? '1' : '0'),
							'status' => intval($image_data['status']),
							'time' => time()
						);
						$res = bool;
						$res = $db->insert($table_video_images,$insert_image);
						
						if(!$res)
						{
							$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage("вставка данных фотографии $i провалилось из-за ошибки при INSERT в БД!",__FILE__,__LINE__).'</p>';
							$error = true;
							break;
						}
						else $item['images'][$i]['id'] = $db->last_id();
					}
				}
			}
			if(isset($_FILES))
			{
				$upload_errors = false;
				$images = array();
				$videos = array();
				if(isset($_FILES['item']['name']['images']))
				{
					foreach($_FILES['item']['name']['images'] as $n => $name)
					{
						$images[$n] = array(
							'name' => $name['file'],
							'tmp_name' => $_FILES['item']['tmp_name']['images'][$n]['file'],
							'error' => $_FILES['item']['error']['images'][$n]['file'],
							'type' => $_FILES['item']['type']['images'][$n]['file'],
							'size' => $_FILES['item']['size']['images'][$n]['file']
						);
					}
				}
				if(isset($_FILES['item']['name']['videos']))
				{
					foreach($_FILES['item']['name']['videos'] as $n => $name)
					{
						$videos[$n] = array(
							'name' => $name['file'],
							'tmp_name' => $_FILES['item']['tmp_name']['videos'][$n]['file'],
							'error' => $_FILES['item']['error']['videos'][$n]['file'],
							'type' => $_FILES['item']['type']['videos'][$n]['file'],
							'size' => $_FILES['item']['size']['videos'][$n]['file']
						);
					}
				}
				if(!empty($images))
				{
					foreach($images as $key=>$file)
					{
						if($file['name'] != '' and $file['error'] == '0' and $file['size'] > '0')
						{
							if(isset($item['images'][$key]['id']) and intval($item['images'][$key]['id']) > 0)
							{
								$name = intval($item['images'][$key]['id']);
							}
							else
							{
								$error = true;break;
							}
							$dir = '/video/images/';$sizes = array(600,300,100);
							$upload_image = upload_image($file,$name,$dir,$sizes);
							if(!$upload_image)
							{
								$upload_errors = true;
								$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage("добавление фотографии $key провалилось из-за ошибки при вставке в БД! Переданный запрос ".$insert_image,__FILE__,__LINE__).'</p>';
								$db->query("DELETE FROM $table_video_images WHERE id = '".$name."'");
								break;
							}
						}
					}
				}
				if(!empty($videos))
				{
					foreach($videos as $key=>$file)
					{
						if($file['file'] != '')
						{
							$name = $key;$dir = '/video/videos/';$sizes = array(600,300,100);
							$upload_image = upload_video_ajax($file,$name,$dir,$sizes);
							if(!$upload_image){$upload_errors = true;$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage($err->getError('ERROR_SQL_INSERT','add_item','video')).'</p>';break;}
						}
					}
				}
				if($upload_errors)
				{header('location: /admin/video/');die();}
				else
				{unset($_FILES);}
			}
			$_SESSION['message'] = '<p class="success">'.$err->constructErrorMessage($err->getError('NO_ERROR','edit_item','video')).'</p>';
			header('location: /admin/video/');die();
		}
		else
		{
			$_SESSION['message'] = '<p class="error">'.$err->constructErrorMessage($err->getError('ERROR_SQL_UPDATE','edit_item','video'),__FILE__,__LINE__).'</p>';
			header('location: /admin/video/');die();
		}
	}
}
/** END 	Edit Item */
//TODO: Item->Delete
/** START 	Delete Item */
elseif($do == 'delete')
{
	
}
/** END 	Delete Item */
/** END 	Add/Edit/Delete Item */
/** START 	//TODO: FILTER
 */
	if(isset($_POST['filter_off']))
	{
		unset($_SESSION['filter']);
		unset($_POST['filter_off']);
	}
	elseif(isset($_POST['filter_on']))
	{
		$filter=$_POST['filter'];
		$_SESSION['filter']=$filter;
		$_SESSION['filter']['status']='on';
		unset($_POST['filter']);
	}
	elseif(isset($_SESSION['filter']))
	{
		$filter=$_SESSION['filter'];
	}
	$sql_clause=array();
	$sql_where='';
	if(isset($filter))
	{
		if($filter['factory']!='0')
			$sql_clause[]= "$table.factory_id='".$filter['factory']."'";
		if($filter['style']!='0')
			$sql_clause[]= "$table.style_id='".$filter['style']."'";
		if($filter['type']!='0')
			$sql_clause[]= "$table.type_id='".$filter['type']."'";
		if(!empty($sql_clause))
			$sql_where=" WHERE ".implode(' AND ',$sql_clause);
	}
/** END 	FILTER **/
/** START 	Формируем список жанров */
	/** родительская категория для видео */
	$parent_category = $db->fetch_one("SELECT p.* FROM $table_category AS p WHERE p.pid = '0' AND p.alias = 'videogenres' AND p.module = 'video'");
	if($parent_category != false)
	{
		$smarty->assign("parent_category",$parent_category);
		/** Жанры видео */
		$categories = $db->fetch_array("SELECT c.* FROM $table_category AS c WHERE c.pid = '".$parent_category['id']."' AND c.status = '2'");
		if($categories != false)
		{
			$smarty->assign("categories",$categories);
			$genres = $db->fetch_list("SELECT title FROM $table_category WHERE c.pid = '".$parent_category['id']."' AND c.status = '2'");
			if(!empty($genres)) $smarty->assign("video_genres",$genres);
		}
	}
/** END 	Формируем список жанров */
/** START 	//TODO: Items
 */
	$items = $db->fetch_array("
	SELECT SQL_CALC_FOUND_ROWS c.*,COUNT(v.id) AS qnty_links,COUNT(i.id) AS qnty_images 
	FROM $table_video_catalog AS c 
	LEFT JOIN $table_video_videos AS v ON c.id = v.pid 
	LEFT JOIN $table_video_images AS i ON c.id = i.pid 
	WHERE c.status = '2' ".$sql_where." 
	GROUP BY c.id 
	ORDER BY c.time DESC 
	LIMIT $lim_from,$per_page");
	if($items != false)
	{
		$quantity = $db->fetch_one(QUANTITY);
		$per_page_navigation = ceil($quantity[0]/$per_page);
		if($quantity[0]>0)
		{
			foreach($items as $k=>$v)
			{
				$main_image = array();
				$sql_main_image = "SELECT * FROM $table_video_images WHERE pid = '".$v['id']."' AND main = '1' AND status = '2'";
				$main_image = $db->fetch_one($sql_main_image);
				
				if(!empty($main_image))
				{
					$main_image['src'] = UPLOAD.$this->dir."/images/".$main_image['id'];
					$items[$k]['main_image'] = $main_image;
				}
				else $items[$k]['main_image'] = false;
			}
			$smarty->assign("kolvo",$quantity[0]);
			$smarty->assign("items",$items);
			$smarty->assign("ppn",$per_page_navigation);
			//print_var($items);
		}
	}
/** END 	Items */
/** START 	//TODO: Item
 */
	$images_num = 0;
	$videos_num = 0;
	if($item_id > 0)
	{
		$item = $db->fetch_one("
		SELECT c.*,COUNT(v.id) AS qnty_links,COUNT(i.id) AS qnty_images  
		FROM $table_video_catalog AS c 
		LEFT JOIN $table_video_videos AS v ON c.id = v.pid 
		LEFT JOIN $table_video_images AS i ON c.id = i.pid 
		WHERE c.id = '$item_id' 
		GROUP BY c.id
		");
		if($item != false)
		{
			$item['images'] = $db->fetch_array("SELECT * FROM $table_video_images WHERE pid = '$item_id'");
			if(!empty($item['images']))
			{
				foreach($item['images'] as $n=>$image)
				{
					$item['images'][$n]['src'] = UPLOAD.$this->dir."/images/".$image['id'];
				}
			}
			$item['videos'] = $db->fetch_array("SELECT * FROM $table_video_videos WHERE pid = '$item_id'");
			if(!empty($item['videos']))
			{
				
			}
			$images_num = $item['qnty_images'];
			$videos_num = $item['qnty_links'];
			$smarty->assign("item",$item);
		}
		$do = 'edit';
	}
	else
	{
		$do = 'add';
	}
	$smarty->assign("images_num",$images_num);
	$smarty->assign("videos_num",$videos_num);
/** END 	Item */
if(isset($_SESSION['message']) and !empty($_SESSION['message']))
{$smarty->assign("message",strval($_SESSION['message']));unset($_SESSION['message']);}
$smarty->assign("do",$do);
$smarty->assign("per_page",$per_page);
$smarty->assign("from",$from);
?>